import { has } from 'lodash-es'
import type { MockMethod } from 'vite-plugin-mock'

import {
  mockDateUnix,
  resultError,
  resultPageSuccess,
  resultSuccess
} from './_util'

const userInfo = {
  id: '@id',
  username: 'Ervin Howell',
  account: 'admin',
  email: '@email',
  login_addr: '@county(true)',
  login_ip: '@ip',
  created_at: mockDateUnix(),
  login_at: mockDateUnix()
}

const dataSource = Array.from({ length: 297 }, () => ({
  _: '@increment',
  id: '@id',
  user_name: '@name',
  login_address: '@county(true)',
  login_time: mockDateUnix(),
  login_ip: '@ip',
  login_addr: '@county(true)',
  system_info: '121444',
  browser_info: '45451',
  device_info: '7885'
}))

const loginLogDataSource = Array.from({ length: 297 }, () => ({
  _: '@increment',
  id: '@id',
  username: '@name',
  ip: '@ip',
  login_address: '@county(true)',
  login_time: mockDateUnix(),
  browser_version: '@name',
  system_version: '@name'
}))

const prefix = 'v1/session'

export default [
  {
    method: 'post',
    url: `/mock/${prefix}`,
    statusCode: 200,
    response: ({ body }: any) => {
      const res = {
        token:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzUwNjIwMjksImp0aSI6IjFAMTU5NjA0MjUxNTQ2OTgzMjE5MiJ9.BcLHC0Vhks8EZTGU0znOr2vRNAL9OEJTKquVhx8G7iQ',
        admin: userInfo
      }
      if (has(body, 'password') && has(body, 'username')) {
        return body.username === 'admin' && body.password === 'abcd.1234'
          ? resultSuccess(res)
          : resultError('请输入正确账号/密码')
      }
      if (has(body, 'email') && has(body, 'code')) {
        return body.email === 'admin@gmail.com' && body.code === '937662'
          ? resultSuccess(res)
          : resultError('请输入正确邮箱/验证码')
      }
      return resultError('请输入正确账号/密码')
    }
  },
  {
    method: 'delete',
    url: `/mock/${prefix}`,
    statusCode: 200,
    response: () => resultSuccess(userInfo)
  },
  {
    method: 'get',
    url: '/mock/user/info',
    statusCode: 200,
    response: () => resultSuccess(userInfo)
  },
  {
    method: 'get',
    url: '/mock/user/list',
    statusCode: 200,
    response: ({
      query
    }: {
      query: { keywords?: string; offset?: number; limit?: number }
    }) => {
      // const predicate = ({ username }: UserModel) => {
      //   return (
      //     username.indexOf(query.keywords!) > -1
      //   )
      // }
      // const res = query?.keywords ? dataSource.filter(predicate) : dataSource
      return resultPageSuccess(
        Number(query?.offset ?? 0),
        Number(query?.limit ?? 10),
        dataSource
      )
    }
  },
  {
    method: 'get',
    url: '/mock/v1/admin_login_record',
    statusCode: 200,
    response: ({ query }: { query: { offset?: number; limit?: number } }) => {
      return resultPageSuccess(
        Number(query?.offset ?? 0),
        Number(query?.limit ?? 10),
        loginLogDataSource
      )
    }
  }
] as MockMethod[]
